<?php


namespace App\Utils;

use App\Constants\DefaultValue;
use App\Constants\ErrorCode;
use App\Constants\RedisKey;
use App\Exception\BusinessException;
use EasySwoole\VerifyCode\Conf;
use EasySwoole\VerifyCode\VerifyCode;
use Hyperf\Redis\RedisFactory;
use Hyperf\Validation\ValidationRuleParser;

/**
 * 图形验证码
 * Class Captcha
 * @package App\Utils
 */
class Captcha
{
    /**
     * @var \Hyperf\Redis\RedisProxy|mixed|\Redis|null
     */
    protected $redis;

    public function __construct()
    {
        $this->redis = di(RedisFactory::class)->get('default');
    }


    /**
     * 生成验证码
     * @return mixed
     */
    public function getCaptcha()
    {
        $config = new Conf();
        $config->setCharset('0123456789');
        $VCode = new VerifyCode($config);
        $code = $VCode->DrawCode();

        mt_srand();
        $key = time() . mt_rand(1, 1000000);

        $this->redis->setex(RedisKey::VERIFY_CODE_IMG . $key, DefaultValue::IMAGE_CAPTCHA_TTL, $code->getImageCode());

        return [
            'key' => $key,
            'verify_code' => $code->getImageBase64()
        ];
    }


    public function checkCaptcha($key, $code): bool
    {
        if (\env('APP_ENV') != 'pro') {
            return true;
        }

        $sCode = $this->redis->get(RedisKey::VERIFY_CODE_IMG . $key);

        $this->redis->del(RedisKey::VERIFY_CODE_IMG . $key);

        if (!$code || !$sCode) {
            throw new BusinessException(ErrorCode::CAPTCHA_EXPIRED);
        }
        if ($code != $sCode) {
            throw new BusinessException(ErrorCode::CAPTCHA_VALIDATE_ERROR);
        }
        return true;
    }


}